package com.eternal.widget;

import android.graphics.Canvas;
import androidx.annotation.IdRes;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.ItemTouchHelper;
import android.view.View;

/**
 * @author Administrator
 */
public class MarkItemCallBack extends MarkItemTouchHelper.Callback {
    private boolean isCanSwipe;
    private int front;
    private int back;

    public MarkItemCallBack(@IdRes int front, @IdRes int back) {
        this.front=front;
        this.back=back;
    }

    public MarkItemCallBack setCanSwipe(boolean canSwipe) {
        isCanSwipe = canSwipe;
        return this;
    }

    @Override
    public boolean isItemViewSwipeEnabled() {
        return isCanSwipe;
    }

    @Override
    public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
        int dragFlags = 0;
        int swipeFlags = 0;

        if (layoutManager instanceof GridLayoutManager) {
            dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
            swipeFlags = 0;
        } else if (layoutManager instanceof LinearLayoutManager) {
            if ((((LinearLayoutManager) layoutManager).getOrientation() == LinearLayoutManager.VERTICAL)) {
                dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
                swipeFlags = ItemTouchHelper.LEFT ;
            } else {
                swipeFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
                dragFlags = ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
            }

        }
        return makeMovementFlags(dragFlags, swipeFlags);
    }

    @Override
    public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder
            target) {
        return true;
    }

    @Override
    public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
    }

    @Override
    public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float
            dY, int actionState, boolean isCurrentlyActive) {
        if (actionState == MarkItemTouchHelper.ACTION_STATE_SWIPE) {
            int translateX = viewHolder.itemView.findViewById(back).getWidth();
            View contentView = viewHolder.itemView.findViewById(front);
            if (contentView == null){
                return;
            }
            if (dX < -translateX) {
                dX = -translateX;
                contentView.setTranslationX(dX);
            } else {
                contentView.setTranslationX(dX);
            }
        } else {
            super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
        }
    }
}